<template>
  <el-dialog
    :title="title"
    :visible.sync="dialogVisible"
    :width="width"
    :append-to-body="appendToBody"
    :close-on-click-modal="!saving"
    :close-on-press-escape="!saving"
    :show-close="!saving"
    custom-class="dialog-style"
  >
    <el-form ref="form" :model="form" :rules="inputRules" label-position="top">
      <!-- <div v-if="text !== ''" class="detail">{{ text }}</div> -->
      <el-form-item :label="text" prop="input">
        <el-input v-model="form.input" :disabled="saving === true" placeholder="内容" @change="$emit('change', form.input)" />
      </el-form-item>
    </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button v-if="!saving" @click="dialogVisible = false">{{ cancel }}</el-button>
      <el-button type="primary" :loading="saving" @click="handleOk">{{ ok }}</el-button>
    </span>
  </el-dialog>
</template>

<script>
export default {
  name: 'TextInput',
  model: {
    prop: 'value',
    event: 'change'
  },
  props: {
    // visible: { type: Boolean, default: false },
    value: { type: String, default: '' },
    text: { type: String, default: '' },
    title: { type: String, default: '输入' },
    width: { type: String, default: '500px' },
    cancel: { type: String, default: '取 消' },
    ok: { type: String, default: '确 定' },
    appendToBody: { type: Boolean, default: true },
    rules: { type: Array, default() { return [] } },
    autoHide: { type: Boolean, default: true }
  },
  data() {
    return {
      dialogVisible: false,
      form: {
        input: ''
      },
      inputRules: {
        input: this.rules
      },
      saving: false,
      extra: null
    }
  },
  watch: {
    value() {
      this.form.input = this.value
    }
  },
  // watch: {
  //   dialogVisible: {
  //     immediate: true,
  //     handler() {
  //       this.$emit('update:visible', this.dialogVisible)
  //     }
  //   },
  //   visible: {
  //     immediate: true,
  //     handler() {
  //       console.log('show')
  //       if (this.dialogVisible !== this.visible) {
  //         this.dialogVisible = this.visible
  //       }
  //     }
  //   }
  // },
  methods: {
    show(extra, setSaving) {
      this.extra = extra
      this.dialogVisible = true
      this.form.input = this.value
      // if (setSaving === undefined) {
      //   this.saving = false
      // } else {
      this.saving = setSaving === true
      // }
    },
    sync(working) {
      this.saving = working === true
    },
    hide() {
      this.dialogVisible = false
      this.saving = false
    },
    handleOk() {
      this.$refs.form.validate((valid) => {
        if (valid) {
          this.$emit('ok', this.extra)
          if (this.autoHide) {
            this.dialogVisible = false
          }
        }
        return valid
      })
    }
  }
}
</script>

<style scoped>
.detail {
  margin-bottom: 10px;
}
</style>
